package com.gonfre.quientelo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

import util.CustomAutoCompleteView;
import util.FilterValues;
import util.MyDBObject;
import util.MyDataBase;
import util.MyFieldObject;
import util.MyParameters;
import util.Response;
import util.Tools;

/**
 * Created by Tecnocom on 1/14/2015.
 */
public abstract class MyActivity extends ActionBarActivity {

    protected Bundle params = null;
    protected String activityToBack = null;
    protected String key = null;
    protected Toolbar toolbar = null;
    protected boolean hasMenu = false;
    protected Toolbar filterBar;
    protected Toolbar sorterBar;

    public MyDataBase dbLocations;
    //public CustomAutoCompleteView myAutoComplete;
    //public ArrayAdapter<MyDBObject> myAdapter;

    //public CustomAutoCompleteView myAutoCompletes[];
    public ArrayList <CustomAutoCompleteView> myAutoCompletes;
    public ArrayList <ArrayAdapter<MyDBObject>> myAdapters;

    public abstract void onFinishRequest(int type, Response res);

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        getParams();

    }

    public void startProgressBarCircular(int id){
        FrameLayout layout = (FrameLayout)findViewById(id);
        layout.setVisibility(View.VISIBLE);
    }

    public void stopProgressBarCircular(int id){
        FrameLayout layout = (FrameLayout)findViewById(id);
        layout.setVisibility(View.GONE);
    }

    public String getKey(){
        SharedPreferences settings = getSharedPreferences(getString(R.string.preference_file), 0);
        return settings.getString("key",getString(R.string.guest_key));
    }

    public void setKey(String k){
        SharedPreferences settings = getSharedPreferences(getString(R.string.preference_file), 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("key", k);
        editor.commit();
    }

    public String getLang(){
        SharedPreferences settings = getSharedPreferences(getString(R.string.preference_file), 0);
        return settings.getString("lang", getString(R.string.default_lang));
    }

    public void setLang(String l){
        SharedPreferences settings = getSharedPreferences(getString(R.string.preference_file), 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("lang", l);
        editor.commit();
    }

    public String getPreference(String attr, String def){
        SharedPreferences settings = getSharedPreferences(getString(R.string.preference_file), 0);
        return settings.getString(attr, def);
    }

    public int getPreference(String attr, int def){
        SharedPreferences settings = getSharedPreferences(getString(R.string.preference_file), 0);
        return Integer.parseInt(settings.getString(attr, ""+def));
    }

    public void setPreference(String attr, String val){
        SharedPreferences settings = getSharedPreferences(getString(R.string.preference_file), 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(attr, val);
        editor.commit();
    }

    public int getVersionDB(String table){
        int res = getPreference("DB"+table+"_VERSION", Integer.parseInt(getString(R.string.version_ubicacion)));
        return res;
    }

    public void setVersionDB(String table, String version){
        setPreference("DB"+table+"_VERSION", version);
    }

    public String getDBTable(String table){
        return "DB"+table;
    }


	protected void getParams() {
        try {
            //get toolbar
            this.toolbar = (Toolbar) findViewById(R.id.toolbar);

            setSupportActionBar(this.toolbar);

            //Get params
            this.params = getIntent().getExtras();
            try {
                key = params.getString("key");
            } catch (Exception _e) { }

            //Create action button
            if (!this.hasMenu) {
                this.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            activityToBack = params.getString("activityToBack");
                        } catch (Exception _e) {
                        }

                        if (activityToBack == null) {
                            //finishActivity(0);
                            finish();
                            return;
                        }

                        if (activityToBack.equals("Login")) {
                            Intent intent = new Intent(MyActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        } else { //vacio

                        }
                    }
                });
            }

        } catch (Exception _e) {
            // if exception, there is not toolbar
        }
    }

    public final static boolean validateEmail(CharSequence target) {
        if (target == null)
            return false;
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }

    protected boolean validatePass(String p1, String p2){
        boolean b;
        if(p1.compareTo(p2) == 0)
            b = true;
        else
            b = false;
        return b;
    }

    protected String getViewValueStr(int id){
        String v;
        TextView t0 = (TextView)findViewById(id);
        v = t0.getText().toString();
        return v;
    }

    protected int getViewValueInt(int id){
        int v;
        TextView t1 = (TextView)findViewById(id);
        try{
            v = Integer.parseInt(t1.getText().toString().replace(".",""));
        }catch (Exception e){
            v = -999;
        }
        return v;
    }

    protected int getCustomViewValueInt(int id){
        int v;
        CustomAutoCompleteView t1 = (CustomAutoCompleteView)findViewById(id);
        try{
            v = Integer.parseInt(t1.getItemId());
        }catch (Exception e){
            v = -999;
        }
        return v;
    }

    public String getShortLocationName(String name){
        int nroNiveles = Integer.parseInt(getString(R.string.niveles_short_location));
        String res = "";
        String[] nameArray = name.split(",");
        for (int i = 0; i < nroNiveles; i++) {
            res = res + "," + nameArray[i];
        }
        return res.substring(1);
    }


    /* Methods for Second Bars */
    public void onSorterBarOkPressed(int optionSelected) {
        Log.i("SortBar", "OK PRESSED! Option: " + optionSelected);
        if (sorterBar != null) {
            Tools.toggleSecondBar(sorterBar);
        }
    }

    public void onSorterBarCancelPressed() {
        Log.i("SortBar", "CANCEL PRESSED!");
        if (sorterBar != null) {
            Tools.toggleSecondBar(sorterBar);
        }
    }

    protected void initializeSorterBar(int id, int type) {
        SortFragment sorterFragment = (SortFragment)getFragmentManager().findFragmentById(id);
        sorterFragment.setUserType(type);
    }

    protected void initializeFilterBar(int id, int type) {
        FiltersFragment filtersFragment = (FiltersFragment)getFragmentManager().findFragmentById(id);
        filtersFragment.setUserType(type);
    }

    public void onFilterBarOkPressed(FilterValues values) {
        Log.i("FilterBar", "OK PRESSED! Option: " + values.toString());
        if (filterBar != null) {
            Tools.toggleSecondBar(filterBar);
        }
    }

    public void onFilterBarCancelPressed() {
        Log.i("FilterBar", "CANCEL PRESSED!");
        if (filterBar != null) {
            Tools.toggleSecondBar(filterBar);
        }
    }
}
